using System;

using Elev.Core.DBUpdates;

namespace Elev.Core
{
    public enum FileStatus
    {
        Valid,
        Invalid,
        ValidOutdated,
        ValidTooRecent
    }

    /// <summary>
    /// Singleton class to manage contextuel information, such as ConnectionString
    /// </summary>
    public class Context
    {
        static Context instance;
        static readonly object padlock = new object();

        string filePath = string.Empty;
        string connectionString = string.Empty;

        protected Context() { }

        static public Context Current
        {
            get
            {
                lock (padlock)
                {
                    if (instance == null)
                        instance = new Context();

                    return instance;
                }
            }
        }

        public string FilePath
        {
            get { return filePath; }
        }

        public string ConnectionString
        {
            get { return connectionString; }
            set { connectionString = value; }
        }

        public bool IsClassOpened
        {
            get { return (connectionString != ""); }
        }

        public void Close()
        {
            connectionString = string.Empty;
            MetaInfo.Clear();
        }

        public void Open(string db)
        {
            connectionString = SqliteConnectionStringBuilder.GetConnectionString(db);
            filePath = db;
        }

        public FileStatus Check()
        {            
            // Check if the specified file is valid
            int dbVersion = -1;
            try
            {
                dbVersion = MetaInfo.DBVersion; 
            }
            catch (Exception)
            {
                connectionString = "";
                return FileStatus.Invalid;
            }

            // Check if the specified file's version matches the application expectation
            DBUpdater updater = new DBUpdater(dbVersion);
            DBStatus status = updater.GetDBStatus;
            if (status == DBStatus.Outdated)
                return FileStatus.ValidOutdated;
            else if (status == DBStatus.TooNew)
                return FileStatus.ValidTooRecent;
            
            // Everything is ok, proceed            
            return FileStatus.Valid;
        }
    }
}
